package com.qzl.feiq.protocol;

import com.qzl.feiq.config.FeiQCache;
import com.qzl.feiq.enu.MessageTypeEnum;
import com.qzl.feiq.message.AdditionalSection;
import com.qzl.feiq.message.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.qzl.feiq.config.StaticConfig;

import java.util.ArrayList;

/**
 * 将接收到的DatagramPacket转换为message方便处理
 */
// UDP 是基于数据报的协议，Netty 中默认接收到的是 DatagramPacket，如果你的解码器只处理 ByteBuf 或其他类型（如继承了 ByteToMessageDecoder），是不会被触发的。
@Slf4j
public class UdpSimple2Message extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String ip = msg.sender().getAddress().toString().replace("/","");
        boolean contains = FeiQCache.allIps.contains(ip);
        String content = msg.content().toString(StaticConfig.CHARSET);
        if (!contains){
            if (!content.contains("6291459")) {
                log.info("Udp接收到的原始对象: {}" , content);
            }
            Message message = datagramPacket2Message(content);
            message.setFromUserIp(ip);
            message.setMessageType(MessageTypeEnum.message);
            message.setRawData(content);
            // 传递到下一个handler， 由下一个handler处理
            ctx.fireChannelRead(message);
        } else {
//            log.info("Udp接收到自己的数据: {}" , content);
        }
    }

    private Message datagramPacket2Message(String content) {
        Message message = new Message();
        if (StringUtils.isNotBlank( content)){
            String[] split = content.split(StaticConfig.SEPARATOR);
            message.setSenderName(split[2].trim());
            message.setSenderHost(split[3].trim());
            message.setCommand(Integer.parseInt(split[4].trim()));
            message.setMsg(split[5].trim());
            ArrayList<AdditionalSection> additionalSections = new ArrayList<>();
            // 有文件相关的数据
            if (split.length >= 6){
                for (int i = 6; i < split.length; i+=5) {
                    AdditionalSection additionalSection = new AdditionalSection();
                    additionalSection.setFileName(split[i].trim());
                    additionalSection.setFileSize(Long.parseLong(split[i+1].trim(), 16));
                    additionalSection.setCreateTime(split[i+2].trim());
                    additionalSection.setFileType(Integer.parseInt(split[i+3].trim()));
                    additionalSection.setEnd(split[i+4].trim());
                    additionalSections.add(additionalSection);
                }
            }
            message.setAdditionalSections(additionalSections);
        }
        return message;
    }
}
